import '../../util/_base_export.dart';
import '../../util/_view_export.dart';

import '../../blocs/cart.dart';
import '../../blocs/product.dart';

class OrderCartScreen extends StatefulWidget {
  OrderCartScreen({Key? key}) : super(key: key);
  _OrderCartScreenState createState() => _OrderCartScreenState();
}

class _OrderCartScreenState extends State<OrderCartScreen> {
  @override
  void initState() {
    super.initState();
  }

  GlobalKey cartKey = GlobalKey();

  _login(BuildContext context) {
    App.router.navigateTo(context, AppRoutes.loginSignin);
  }

  _cancel() {}

  @override
  Widget build(BuildContext context) {
    return Consumer<CartBloc>(
      builder: (context, _cart, child) => Builder(
        builder: (context) {
          return Scaffold(
            appBar: AppBar(
              leadingWidth: 33.w,
              backgroundColor: Colors.white,
              brightness: Brightness.light,
              leading: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  Navigator.pop(context);
                },
                child: Container(
                  child: Icon(
                    Icons.chevron_left,
                    color: AppColor.blackMain,
                    size: 32,
                  ),
                ),
              ),
              title: Row(
                children: <Widget>[
                  Text(
                    '购物车',
                    style: TextStyle(color: AppColor.blackMain),
                  ),
                  Text(
                    '  (${_cart.amount})',
                    style: TextStyle(color: AppColor.yellowMain),
                  ),
                ],
              ),
            ),
            body: Container(
              padding: EdgeInsets.only(bottom: 100.h),
              child: Builder(
                builder: (context) {
                  if (_cart.items == null)
                    return Container(width: 0, height: 0);
                  else
                    return ListView.builder(
                      itemCount: _cart.items.length,
                      itemBuilder: (BuildContext context, int index) {
                        var _item = _cart.items[index];
                        print(_item);
                        return Column(
                          children: <Widget>[
                            Slidable(
                              actionPane: SlidableDrawerActionPane(),
                              actionExtentRatio: 0.25,
                              child: Container(
                                color: Colors.white,
                                child: _productItemBlock(_item, _cart),
                              ),
                              secondaryActions: <Widget>[
                                IconSlideAction(
                                  caption: '删除',
                                  color: Colors.black,
                                  icon: Icons.delete,
                                  onTap: () {
                                    _cart.removeItem(_item['sku_id']);
                                  },
                                ),
                              ],
                            ),
                            Divider(
                              height: 1.0,
                              indent: 20.0,
                              endIndent: 20.0,
                            ),
                          ],
                        );
                      },
                    );
                },
              ),
            ),
            floatingActionButtonLocation:
                // FloatingActionButtonLocation.centerDocked,
                FloatingActionButtonLocation.centerFloat,
            floatingActionButton: Container(
              height: 80.h,
              width: 375.w,
              child: GestureDetector(
                  onTap: () async {
                    if ((AppSession.authortoken ?? '').isEmpty)
                      AppPopupService.showAlertSimple(
                        'I',
                        '请先登录',
                        '',
                        iv_cancel_text: '先不了',
                        cancel: _cancel,
                        iv_confirm_text: '去登录',
                        confirm: _login(context),
                      );
                    else {
                      var lv_co = await _cart.checkoutInit();
                      if (lv_co) {
                        App.router.navigateTo(context, AppRoutes.orderCheckout);
                      } else {
                        // msg;
                      }
                    }
                  },
                  child: Container(
                    width: 375.w,
                    color: Color(0xffF8F8F8),
                    child: Row(children: <Widget>[
                      Container(
                          width: 225.w,
                          child: Container(
                            child: Center(
                                child: Text(
                              '共计: \$${_cart.subtotal.toStringAsFixed(2)}',
                              style: TextStyle(
                                fontSize: 18.sp,
                                color: Color(0xffFF9F05),
                              ),
                            )),
                          )),
                      Container(
                          width: 150.w,
                          child: Container(
                            height: 80.h,
                            color: Color(0xffFFB91A),
                            child: Center(
                              child: Text(
                                '去结算',
                                style: TextStyle(
                                  fontSize: 18.sp,
                                ),
                              ),
                            ),
                          ))
                    ]),
                  )),
            ),
          );
        },
      ),
    );
  }

  Widget _productItemBlock(Map item, CartBloc ib_cart) {
    late Offset temp;
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {},
        child: Container(
            width: 343.w,
            height: 162.h,
            padding: EdgeInsets.only(left: 20.w, right: 12.w, top: 18.h),
            child: Column(children: [
              Row(
                children: <Widget>[
                  Container(
                    width: 80.w,
                    height: 80.h,
                    margin: EdgeInsets.only(
                      right: 27.w,
                    ),
                    child: CachedNetworkImage(
                      imageUrl: item['image_url'],
                      fit: BoxFit.cover,
                    ),
                  ),
                  Container(
                    width: 202.w,
                    height: 125.h,
                    padding: EdgeInsets.only(
                      left: 12.w,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                            height: 97.h,
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Container(
                                    child: Text(
                                      item['name'] ?? '',
                                      softWrap: true,
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        color: AppColor.nameProduct,
                                        fontWeight: FontWeight.w500,
                                        fontSize: 12.sp,
                                      ),
                                    ),
                                  ),
                                  SizedBox(height: 4.7.h),
                                  Text(
                                    item['sku_desc'] ?? '',
                                    softWrap: true,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                      color: AppColor.descProduct,
                                      fontWeight: FontWeight.normal,
                                      fontSize: 10.sp,
                                    ),
                                  ),
                                  SizedBox(height: 5.h),
                                  item['outstock_info'] == 1
                                      ? Container(
                                          width: 90.w,
                                          padding: EdgeInsets.symmetric(
                                              horizontal: 5.w),
                                          height: 16.h,
                                          decoration: BoxDecoration(
                                            color: Color(0xffFDE3E3),
                                            borderRadius:
                                                BorderRadius.circular(2),
                                          ),
                                          child: Center(
                                              child: Text('库存不足',
                                                  style: TextStyle(
                                                    color: Color(0xffFF3434),
                                                    fontSize: 10.sp,
                                                  ))))
                                      : Container(),
                                  SizedBox(height: 5.h),
                                  Container(
                                    height: 14.h,
                                    child: Text(
                                      '\$' +
                                          (item['price'] ?? '') +
                                          '/' +
                                          (item['unit_desc'] ?? ''),
                                      softWrap: true,
                                      maxLines: 1,
                                      style: TextStyle(
                                        color: AppColor.nameProduct,
                                        fontWeight: FontWeight.normal,
                                        fontSize: 12.sp,
                                      ),
                                    ),
                                  ),
                                ])),
                        Row(children: [
                          SizedBox(width: 88.w),
                          Column(children: [
                            Container(
                              width: 100.w,
                              height: 28.h,
                              child: Consumer<CartBloc>(
                                builder: (context, _cart, child) => Builder(
                                  builder: (context) {
                                    return Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: <Widget>[
                                        GestureDetector(
                                          onTap: () {
                                            ib_cart.reduceItem(item['sku_id']);
                                          },
                                          child: Icon(
                                            // MaterialCommunityIcons.minus_circle_outline,
                                            LineIcons.minusCircle,
                                            color: AppColor.nameProduct,
                                            size: 24,
                                          ),
                                        ),
                                        Container(
                                          padding: EdgeInsets.symmetric(
                                              horizontal: 14.w),
                                          alignment: Alignment.center,
                                          child: Text(
                                            ib_cart
                                                .itemAmount(item['sku_id'])
                                                .toString(),
                                            style: TextStyle(
                                              color: AppColor.nameProduct,
                                              fontWeight: FontWeight.normal,
                                              fontSize: 20.sp,
                                            ),
                                          ),
                                        ),
                                        GestureDetector(
                                          onPanDown: (details) {
                                            temp = new Offset(
                                                details.globalPosition.dx,
                                                details.globalPosition.dy);
                                          },
                                          onTap: () {
                                            late Function callback;
                                            // setState(() {
                                            ib_cart.addItem(item);
                                            OverlayEntry entry =
                                                OverlayEntry(builder: (ctx) {
                                              return ParabolaAnimateWidget(
                                                AppSession.homeRoot,
                                                temp,
                                                AppSession.homeCart,
                                                Icon(
                                                  Icons.add_circle,
                                                  color: Colors.redAccent,
                                                ),
                                                callback,
                                                duration: 800,
                                              );
                                            });

                                            callback = (status) {
                                              if (status ==
                                                  AnimationStatus.completed) {
                                                entry.remove();
                                              }
                                            };

                                            Overlay.of(AppSession.homeRoot.currentContext!)!.insert(entry);
                                          },
                                          child: Icon(
                                            // MaterialCommunityIcons.plus_circle,
                                            LineIcons.plusCircle,
                                            color: AppColor.nameProduct,
                                            size: 24,
                                          ),
                                        ),
                                      ],
                                    );
                                  },
                                ),
                              ),
                            ),
                          ])
                        ])
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 17.h),
              Divider(
                color: Color(0xffcAcAcA),
                height: 1.0,
                indent: 0.0,
                endIndent: 0.0,
              ),
            ])));
  }
}
